package com.amumu.drama.common.modules.service.impl.payment.handler;

import cn.hutool.json.JSONUtil;
import com.amumu.drama.common.config.WXProperties;
import com.amumu.drama.common.constant.*;
import com.amumu.drama.common.exception.Asserts;
import com.amumu.drama.common.modules.order.dao.PortalOrderDao;
import com.amumu.drama.common.modules.order.dto.OmsOrderDetail;
import com.amumu.drama.common.modules.order.manager.OrderManager;
import com.amumu.drama.common.modules.service.impl.payment.PaymentFactory;
import com.amumu.drama.common.modules.service.impl.payment.PaymentReq;
import com.amumu.drama.common.modules.service.impl.payment.PaymentResp;
import com.amumu.drama.common.modules.sumapay.dto.req.AsyncResultReq;
import com.amumu.drama.common.modules.sumapay.dto.req.WeChatSingleOrderQueryReq;
import com.amumu.drama.common.modules.sumapay.dto.req.WechatPayReq;
import com.amumu.drama.common.modules.sumapay.dto.resp.WeChatPaySuccessResp;
import com.amumu.drama.common.modules.sumapay.dto.resp.WechatPayResp;
import com.amumu.drama.common.modules.sumapay.service.impl.WechatPayServiceImpl;
import com.amumu.drama.model.OmsOrderItem;
import com.amumu.drama.model.UmsMember;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
@EnableConfigurationProperties(WXProperties.class)
public class WXPaymentHandler implements PaymentHandler {


    private WXProperties wxProperties;

    @Autowired
    private OrderManager orderManager;

    @Autowired
    private WechatPayServiceImpl wechatPayService;

    @Autowired
    private PortalOrderDao portalOrderDao;


    @Override
    public String[] type() {
        return new String[]{
                PaymentFactory.getPayHandlerType(PayTypeEnum.WX_PAY, PayProviderEnum.SUMA_PAY, SourceTypeEnum.UNKNOWN),
                PaymentFactory.getPayHandlerType(PayTypeEnum.WX_PAY, PayProviderEnum.SUMA_PAY, SourceTypeEnum.APP),
                PaymentFactory.getPayHandlerType(PayTypeEnum.WX_PAY, PayProviderEnum.SUMA_PAY, SourceTypeEnum.PC),
        };
    }

    @Override
    public PaymentResp pay(PaymentReq param) {

        OmsOrderDetail orderDetail = param.getOrderDetail();

        List<OmsOrderItem> orderItemList = orderDetail.getOrderItemList();
        OmsOrderItem omsOrderItem = orderItemList.get(0);
        UmsMember umsMember = param.getUmsMember();
        log.info("开始进行微信支付");
        try {
            PaymentResp paymentResp = new PaymentResp();
            WechatPayReq request = new WechatPayReq();
            request.setRequestId(orderDetail.getOrderSn());
            request.setTotalPrice(orderDetail.getPayAmount().toString());
            request.setGoodsDesc(omsOrderItem.getProductName());
            //生成商品编码和商品名称

            int size = orderItemList.size();
            for (int i = 0; i < size; i++) {
                boolean isLast = i == size - 1;
                OmsOrderItem orderItem = orderItemList.get(i);
                //将商品信息进行拼接
                request.setProductId((request.getProductId() == null ? "" : request.getProductId()) + orderItem.getProductId() + (isLast ? "" : ","));
                request.setProductName((request.getProductName() == null ? "" : request.getProductName()) + orderItem.getProductName() + (isLast ? "" : ","));
                request.setFund((request.getFund() == null ? "" : request.getFund()) + orderItem.getProductPrice() + (isLast ? "" : ","));
                request.setMerAcct((request.getMerAcct() == null ? "" : request.getMerAcct().trim()) + orderItem.getProductSkuId() + (isLast ? "" : ","));
                request.setBizType((request.getBizType() == null ? "" : request.getBizType()) + orderItem.getProductCategoryId() + (isLast ? "" : ","));
                request.setProductNumber((request.getProductNumber() == null ? "" : request.getProductNumber()) + orderItem.getProductQuantity() + (isLast ? "" : ","));

            }
            WechatPayResp payResp = null;
            paymentResp.setRespInfo(JSONUtil.toJsonStr(request));
            try {
                payResp = wechatPayService.createOrder(request);
            } catch (Exception e) {
                //更新订单状态为支付失败
                paymentResp.setPayRemark(e.getMessage());
                log.error("丰付支付生成订单微信支付失败", e);
                paymentResp.setPayStatusEnum(PayStatusEnum.FAIL);
                paymentResp.setPayRemark(e.getMessage());
            }
            String respJson = JSONUtil.toJsonStr(payResp);
            log.info("payment result {}", respJson);
            paymentResp.setRespInfo(respJson);
            paymentResp.setPayRemark(payResp.getErrorMsg());
            paymentResp.setApplyTime(LocalDateTime.now());
            paymentResp.setPayUrl(payResp.getPayUrl());
            if (Objects.equals(payResp.getResult(), SumapayResultConstants.SUCCESS)) {
                paymentResp.setPayStatusEnum(PayStatusEnum.SUCCESS);

            } else {
                paymentResp.setPayStatusEnum(PayStatusEnum.FAIL);
                paymentResp.setPayRemark(payResp.getErrorMsg());
            }
            return paymentResp;
        } catch (Exception e) {
            log.error("{} 丰付支付微信付款失败 error {}", param, e.getMessage());
            throw e;
        }
    }


    /**
     * 查询订单的支付状态
     *
     * @param orderDetail
     */
    @Override
    public PaymentResp queryPayStatus(OmsOrderDetail orderDetail) {
        PaymentResp resp = new PaymentResp();
        WeChatSingleOrderQueryReq request = new WeChatSingleOrderQueryReq();
        request.setRequestId(orderDetail.getOrderSn());
        request.setOriginalRequestId(orderDetail.getOrderSn());
        WeChatPaySuccessResp paySuccessResp = wechatPayService.singleQuery(request);
        if (resp != null && SumapayResultConstants.SUCCESS.equals(paySuccessResp.getResult())) {
            resp.setPayStatusEnum(PayStatusEnum.SUCCESS);
        } else {
            resp.setPayStatusEnum(PayStatusEnum.PAYING);
        }
        return resp;
    }

    /**
     * 支付回调通知
     *
     * @param params body
     */
    @Override
    public PaymentResp payNotify(Map<String, String> params, String body) {
        PaymentResp paymentResp = new PaymentResp();
        paymentResp.setPayRemark("success");
        AsyncResultReq resultReq = JSONUtil.parse(params).toBean(AsyncResultReq.class);
        OmsOrderDetail orderDetail = portalOrderDao.getDetailByPayOrderSn(resultReq.getRequestId());
        if (orderDetail == null) {
            log.error("orderDetail {} not exist", resultReq.getRequestId());
            Asserts.fail("订单不存在");
        }
        if (!Objects.equals(orderDetail.getPayStatus(), PayStatusEnum.PAYING.getCode())) {
            log.error("order {} status {} invalid", orderDetail.getId(), orderDetail.getStatus());
            Asserts.fail("订单状态不正确,无法支付");
        }
        String errMsg = "取消支付";
        if (SumapayResultConstants.NOTICE_STATUS_SUCCESS.equals(resultReq.getStatus())) {

        } else {
            paymentResp.setPayStatusEnum(PayStatusEnum.FAIL);
            paymentResp.setPayRemark(errMsg);
        }
        return paymentResp;
    }
}
